#include "MsgWebView.h"

#include <Application.h>
#include <QFile>
#include <QFileDialog>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMessageBox>
#include <QWebChannel>
#include <data/UserInfo.pb.h>
using namespace proto;
// #include "WindowManager.h"

MsgWebView::MsgWebView(QWidget* parent)
    : QWebEngineView(parent) {
    MsgWebPage* page = new MsgWebPage(this);
    setPage(page);

    QWebChannel* channel = new QWebChannel(this);
    msgHtmlObj           = new MsgHtmlObj(this);
    channel->registerObject("external", msgHtmlObj);
    this->page()->setWebChannel(channel);

    // TalkWindowShell* talkWindowShell = WindowManager::getInstance()->getTalkWindowShell();

    // 收信息网页页面初始化
    this->load(QUrl("qrc:/resource/MsgHtml/msgTmpl.html"));
}

MsgWebView::~MsgWebView() {}

void MsgWebView::appendMsg(const QString& msgText) {
    QJsonObject msgObj;
    QString     qsMsg = msgText;

    // 将表情替换为表情图片
    qsMsg.replace("<emoj>", "<img class=\"emoj\" src=\"qrc:/resource/img/emojiqq/");
    qsMsg.replace("</emoj>", "\"/>");
    msgObj.insert("MSG", qsMsg);

    msgObj.insert("picture", Application::Myself().headshot().c_str());
    const QString msg = QJsonDocument(msgObj).toJson(QJsonDocument::Compact);

    this->page()->runJavaScript(QString("appendHtml(%1)").arg(msg));
}

// void MsgWebView::appendFile(const packet::file::FileInfo& info) {
//     QJsonObject msgObj;
//     msgObj.insert("picture", Application::Myself().headshot().c_str());
//     msgObj.insert("url", info.url);
//     const QString strFile = QJsonDocument(msgObj).toJson(QJsonDocument::Compact);
//     qDebug() << "strFile:" << strFile;

//     this->page()->runJavaScript(QString("appendFile(%1)").arg(strFile));
// }

void MsgWebView::recvMsg(const QString& msgText) {
    QJsonObject msgObj;
    QString     qsMsg = msgText;
    qsMsg.replace("<emoj>", "<img src=\"qrc:/resource/img/emojiqq/");
    qsMsg.replace("</emoj>", "\"/>");
    msgObj.insert("MSG", qsMsg);
    // data::FriendInfo& f = DataUtils::users[msg.getFormUserId()];
    // msgObj.insert("picture", user.picture);

    msgObj.insert("picture", talkuserinfo.headshot);

    const QString strMsg = QJsonDocument(msgObj).toJson(QJsonDocument::Compact);
    qDebug() << "strMsg:" << strMsg;

    this->page()->runJavaScript(QString("recvHtml(%1)").arg(strMsg));
}

// void MsgWebView::recvFile(const packet::file::FileInfo& info) {
//     QJsonObject msgObj;
//     msgObj.insert("picture", talkuserinfo.headshot().c_str());
//     msgObj.insert("url", info.url);
//     const QString strFile = QJsonDocument(msgObj).toJson(QJsonDocument::Compact);
//     qDebug() << "strFile:" << strFile;

//     this->page()->runJavaScript(QString("recvFile(%1)").arg(strFile));
// }

void MsgWebView::setUserInfo(const TalkUserInfo& info) {
    talkuserinfo = info;
}

QList<QStringList> MsgWebView::parseHtml(const QString& html) {
    QDomDocument doc;
    doc.setContent(html);
    const QDomElement& root = doc.documentElement();  // 节点元素
    const QDomNode&    node = root.firstChildElement("body");

    return parseDocNode(node);
}

QList<QStringList> MsgWebView::parseDocNode(const QDomNode& node) {
    QList<QStringList> attribute;

    const QDomNodeList& list = node.childNodes();  // 返回所有子节点

    for (int i = 0; i < list.count(); i++) {
        const QDomNode& node = list.at(i);

        if (node.isElement()) {
            // 转换成元素
            const QDomElement& element = node.toElement();

            if (element.tagName() == "img") {
                QStringList attributeList;
                attributeList << "img" << element.attribute("src");
                attribute << attributeList;
            }
            if (element.tagName() == "p") {
                QStringList attributeList;
                attributeList << "text" << element.text();
                attribute << attributeList;
            }

            if (element.hasChildNodes()) {
                attribute << parseDocNode(node);
            }
        }
    }

    return attribute;
}

MsgHtmlObj::MsgHtmlObj(QObject* parent) {
    initHtmlTmpl();
}

MsgHtmlObj::~MsgHtmlObj() {
}

void MsgHtmlObj::initHtmlTmpl() {
    m_msgLHtmlTmpl  = getMsgTmplHtml("msgleftTmpl");
    m_msgRHtmlTmpl  = getMsgTmplHtml("msgrightTmpl");
    m_fileLHtmlTmpl = getMsgTmplHtml("fileleftTmpl");
    m_fileRHtmlTmpl = getMsgTmplHtml("filerightTmpl");
}

QString MsgHtmlObj::getMsgTmplHtml(const QString& code) {
    QFile file(QString(":/resource/MsgHtml/%1.html").arg(code));
    file.open(QFile::ReadOnly);

    QString strData("");
    if (file.isOpen()) {
        strData = QLatin1String(file.readAll());
        file.close();
    }
    else {
        QMessageBox::information(nullptr, "Tips", "Failed to init html!");
    }

    return strData;
}

static inline void moveFile(const QString& sourcePath, const QString& destinationPath) {
    // 创建QFile对象
    QFile file(sourcePath);

    // 尝试移动文件
    if (file.rename(destinationPath)) {
        qDebug() << "File moved successfully.";
    }
    else {
        qWarning() << "Failed to move file. Error: " << file.errorString();
    }
}

void MsgHtmlObj::downloadFile(QString fileurl) {
    qDebug() << "downloadFile:" << fileurl;
    auto filename = QFileDialog::getSaveFileName();
    qDebug() << "getSaveFileName:" << filename;
    // Application::getInstance()->Get(fileurl, [=](QString url) {
    //     moveFile(url, filename);
    // });
}

MsgWebPage::MsgWebPage(QObject* parent) : QWebEnginePage(parent) {
}

bool MsgWebPage::acceptNavigationRequest(const QUrl& url, NavigationType type, bool isMainFrame) {
    // 判断 仅接受 qrc://*.html
    if (url.scheme() == QString("qrc"))
        return true;
    return false;
}
